package com.yellowpage.white.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

public class ReadLog {

	public static List<Map> BufferedReader(String path) throws IOException,
			ParseException {

		List<Map> list = new ArrayList<Map>();
		Map<String, Integer> map = new HashMap<String, Integer>();

		SimpleDateFormat fromtTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		SimpleDateFormat fromtDate = new SimpleDateFormat("yyyy-MM-dd_HH");

		File file = new File(path);
		String fileName = file.getName();
		String serverId = fileName.substring(0, fileName.indexOf("_"));
		String logFileName = fileName.substring(fileName.indexOf("_") + 1);

		if (!file.exists() || file.isDirectory()) {
			throw new FileNotFoundException();
		}

		BufferedReader br = new BufferedReader(new InputStreamReader(
				new FileInputStream(file), "UTF-8"));
		String temp = null;
		temp = br.readLine();
		// List<String> sb = new ArrayList<String>();

		int lineCount = 1;

		while (temp != null) {
			// sb.add(temp + " ");

			String value = temp + "";

			temp = br.readLine();
			value = value.trim();
			if (value == null) {
				continue;
			}
			if (value.equals("")) {
				continue;
			}

			String time = value.substring(0, value.indexOf("{"));
			String str = value.substring(value.indexOf("{"));
			Date date = fromtTime.parse(time);
			Long tostrtime = date.getTime();
			String timeStr = fromtDate.format(tostrtime);

			try {
				JSONObject json = JSONObject.fromObject(str);

				String key = timeStr + "&" + json.get("requesttype") + "&"
						+ json.get("responsecode");
				Integer count = 0;
				if (map.get(key) != null) {
					count = map.get(key);
				}
				map.put(key, ++count);

			} catch (Exception e) {
				System.out.println(">>>>>>>> ReadLog Error:" + path + " :"
						+ lineCount + " :" + str);
				e.printStackTrace();
			}

			lineCount++;

		}
		if (map != null) {
			Iterator i = map.entrySet().iterator();
			while (i.hasNext()) {
				Map<String, String> nspLogSum = new HashMap<String, String>();
				Map.Entry e = (Map.Entry) i.next();
				String key = e.getKey().toString();
				String count = e.getValue().toString();
				String[] timeRequestResponse = key.split("&");

				nspLogSum.put("serverId", serverId);
				nspLogSum.put("logFileName", logFileName);
				nspLogSum.put("logTime", timeRequestResponse[0]);
				nspLogSum.put("requestType", timeRequestResponse[1]);
				nspLogSum.put("responseCode", timeRequestResponse[2]);
				nspLogSum.put("count", count);
				list.add(nspLogSum);

			}
		}

		return list;

	}

}
